#Concatenate Arrays in JavaScript
Explore tagged Tumblr posts
matthewzkrause ¡ 3 days ago
Text
7 Essential JavaScript Features Every Developer Should Know Early.
JavaScript is the backbone of modern web development. Whether you're just starting out or already have some coding experience, mastering the core features of JavaScript early on can make a big difference in your growth as a developer. These essential features form the building blocks for writing cleaner, faster, and more efficient code.
Tumblr media
Here are 7 JavaScript features every developer should get familiar with early in their journey:
Let & Const Before ES6, var was the only way to declare variables. Now, let and const offer better ways to manage variable scope and immutability.
let allows you to declare block-scoped variables.
const is for variables that should not be reassigned.
javascript Copy Edit let count = 10; const name = "JavaScript"; // name = "Python"; // This will throw an error Knowing when to use let vs. const helps prevent bugs and makes code easier to understand.
Arrow Functions Arrow functions offer a concise syntax and automatically bind this, which is useful in callbacks and object methods.
javascript Copy Edit // Traditional function function add(a, b) { return a + b; }
// Arrow function const add = (a, b) => a + b; They’re not just syntactic sugar—they simplify your code and avoid common scope issues.
Template Literals Template literals (${}) make string interpolation more readable and powerful, especially when dealing with dynamic content.
javascript Copy Edit const user = "Alex"; console.log(Hello, ${user}! Welcome back.); No more awkward string concatenation—just cleaner, more intuitive strings.
Destructuring Assignment Destructuring allows you to extract values from objects or arrays and assign them to variables in a single line.
javascript Copy Edit const user = { name: "Sara", age: 25 }; const { name, age } = user; console.log(name); // "Sara" This feature reduces boilerplate and improves clarity when accessing object properties.
Spread and Rest Operators The spread (…) and rest (…) operators may look the same, but they serve different purposes:
Spread: Expands an array or object.
Rest: Collects arguments into an array.
javascript Copy Edit // Spread const arr1 = [1, 2]; const arr2 = […arr1, 3, 4];
// Rest function sum(…numbers) { return numbers.reduce((a, b) => a + b); } Understanding these makes working with arrays and objects more flexible and expressive.
Promises & Async/Await JavaScript is asynchronous by nature. Promises and async/await are the key to writing asynchronous code that reads like synchronous code.
javascript Copy Edit // Promise fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data));
// Async/Await async function getData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } Mastering these will help you handle APIs, databases, and other async operations smoothly.
Array Methods (map, filter, reduce) High-order array methods are essential for transforming and managing data.
javascript Copy Edit const numbers = [1, 2, 3, 4, 5];
// map const doubled = numbers.map(n => n * 2);
// filter const even = numbers.filter(n => n % 2 === 0);
// reduce const sum = numbers.reduce((total, n) => total + n, 0); These methods are clean, efficient, and favored in modern JavaScript codebases.
Final Thoughts Learning these JavaScript features early gives you a solid foundation to write better, more modern code. They’re widely used in frameworks like React, Vue, and Node.js, and understanding them will help you grow faster as a developer.
Start with these, build projects to apply them, and your JavaScript skills will take off.
0 notes
tccicomputercoaching ¡ 5 months ago
Text
Difference between ES5 and ES6
Tumblr media
JavaScript is the must need programming language for both web and software engineering, and it keeps on changing with time. All developers should know the difference between ES5 and ES6 because major variations and advancements were made in those versions. ES5 started the foundation and had shown more advanced features in the version of ECMAScript 2015, also known as ES6. At TCCI Computer Coaching Institute, we ensure that each student understands these updates deeply so that they can be ahead in their programming journey.
What is ES5?
ES5, which stands for ECMAScript 5, was launched in 2009. This is the version of JavaScript which was seen to be stable, and it filled some of the most important holes that were there in the earlier versions. Key features of ES5 include:
Strict Mode: Strict mode allows developers to write secure and optimized code because it throws an error for all actions that are allowed in other versions.
JSON Support: ES5 provided support to work with JSON (JavaScript Object Notation), which is an essential feature for data interchange.
Array Methods: It introduced several new array methods, such as forEach(), map(), filter(), and reduce(), that simplify operations on arrays.
Getter/Setter Methods: ES5 allows the use of getter and setter methods, making it possible to control object properties.
What is ES6?
ES6, also commonly referred to as ECMAScript 2015, was a substantial update to the JavaScript language to include many new features as well as additions that make this language more powerful, concise, and much more modern in its expression. Some of its key features include:
Let and Const: There are let and const, added to declare a variable, with let offering better scoping than var, and const having no redefinition.
Arrow Functions: More concise syntax - also preserves this context.
Template Literals: Template literals ease string interpolation and multiline strings, and are much readable and less error-prone.
Classes: Classes, which are new in ES6, make the syntax for creating objects and handling inheritance much simpler than it used to be. It makes JavaScript resemble other more conventional object-oriented programming languages.
Promises: The promise is how asynchronous code works; promises handle success and failure states much easier.
Destructuring: This helps extract values from arrays and objects into separate variables in a simple syntax.
Modules: ES6 provided modules, where JavaScript code could be broken into reusable, maintainable pieces.
Key differences between ES5 and ES6
Variable declarations:
ES5 : Variables are declared using var.
ES6 : let and const keywords were introduced which provide block scoping and better predictability
Functions:
ES5: The function keyword is used to declare functions, and the this context can be a little tricky in some cases.
ES6: Arrow functions offer a more compact syntax and lexically bind the this keyword, avoiding common problems with this.
Object-Oriented Programming:
ES5: JavaScript uses prototype-based inheritance.
ES6: Introduces the class syntax, making object-oriented programming much more intuitive and easier to use.
Asynchronous Programming:
ES5: Callbacks are typically used for handling asynchronous code.
ES6: It introduced promises that made asynchronous operation cleaner.
Modules:
ES5 JavaScript does not natively support modules. Developers will use libraries such as CommonJS or RequireJS.
ES6 Native module support using the keywords import and export, which facilitates code organization and reusability
Template Literals:
ES5 String concatenation is done by using + operators, which can sometimes be error-prone and messy to read.
ES6 Template literals enable multi-line strings and interpolation of strings, enhancing readability.
Why Is It Important to Learn ES6?
At TCCI Computer Coaching Institute, we understand that staying updated with the latest advancements in JavaScript is crucial for your programming career. Learning ES6 is not just about getting familiar with new syntax, but also about adopting best practices that improve the quality and maintainability of your code.
As the JavaScript community shifts towards ES6 as the norm, most of the modern libraries and frameworks are built using the features of ES6. So, mastering ES6 will help you work with the latest technologies like React, Angular, and Node.js. The difference between ES5 and ES6 will also make you a more efficient developer in writing clean, efficient, and scalable code regardless of whether you are a beginner or a seasoned developer.
Learn ES6 with TCCI Computer Coaching Institute
We provide in-depth JavaScript training classes at TCCI Computer Coaching Institute that covers everything, starting from the basic knowledge of ES5 to the latest features added to ES6 and beyond. We ensure you have hands-on practice by giving practical exercise and real-world projects, along with individual guidance.
Learn at your pace with our online and offline classes.
Expert Trainers: Our trainers are industry experts with years of experience in teaching JavaScript and web development.
Real-World Applications: We focus on real-world programming challenges, ensuring that you are well-prepared for the job market.
It is one of the important steps in becoming a good JavaScript developer, as one should master the differences between ES5 and ES6. We provide the right environment and resources to learn and grow as a developer at TCCI Computer Coaching Institute. Join us today and start your journey toward mastering JavaScript!
Location: Ahmedabad, Gujarat
Call now on +91 9825618292
Get information from https://tccicomputercoaching.wordpress.com/
0 notes
letstacle-online-academy ¡ 3 years ago
Text
Tumblr media
0 notes
raymondsecurityadventures ¡ 6 years ago
Text
Lecture 6
I just remembered that professionalism was part of the portfolio marking criteria so I’ll try to keep it PG in these posts. Meaning that I’m allowed to drop one and only one F-bomb somewhere. 
Avalanching
Recall that the Merkle-Damgard hash construction looked like this: 
Tumblr media
The reason the hash function is segmented into the various f’s you see above, is to allow avalanching to occur; the property that causes good cryptographic hashes to be drastically different from one another, even if the edit distance of the inputs if minimal. This allows for the semantic meaning of relatively similar inputs to be obfuscated, as one would otherwise be able to perhaps glean information pertaining to the information that had been hashed, through observation of the structure of the hash string and comparison with other similar hashes e.g. if hashing 12345 and 12346 produced hashes of 0xaa0geb212r3r3142q and 0xaa0geb212r3r3131w, then an attacker could probably guess the structure of the input at the very least and perhaps interpolate the inputs by generating other hashes. 
Passwords Part II 
From the exam, we might have found that the # of bits of security that we get from a random password using the Elephant Apple Golfing principle (or some shit I don’t remember the stupid name) isn’t as many as we would like. It’s naive to say that a password has as many bits as it is long, unless those bits are truly random and the full complement of ASCII characters are actually utilised, such as \0. Indeed most passwords aren’t that many bits, given that they’re based largely on quotes, names, birthdays etc. etc. and it’s only a matter of time before increases in computing power renders them obsolete.  
So yeah, the answer to that question pertaining to the Homophobic Dog Shagger principle is 40-49 bits i.e. the smallest choice. Congratulations if you got it right. 
This kind of segues into why WEP keys are terrible: 
They’re consisted of a shared 40 bit key, that everyone connected to a network knows, and a 24 bit initialisation vector that was randomly generated locally by the receiver that were combined to form a ‘64′ bit key and this key was used to encrypt every frame.  The obvious issue with this is that it’s trivial to brute force 24 bits, and it’s probably trivial to brute force 40 bits, and it wasn’t too difficult combining all the brute forced combinations to obtain the purported 64 bit key. 
Mixing Control and Data - Smashing the Stack for Fun and Profit 
http://phrack.org/issues/49/14.html
Mixing control and data is bad, don’t do it.  C lets us do it and although most modern compilers such as gcc and clang have several countermeasures for stack smashing, it remains a useful case study and a common issue in modern software. 
Buffer overflows can occur when someone writes shit code and rather than fixing declaring a fixed array size in their loop iteration, they end the array loop once the program hits NULL, allowing a third-party to use a function such as strcpy() - that doesn’t check buffer size - to stuff more in the buffer than has been allocated to memory. There are other methods too but this is the most intuitive to understand. 
The Stack and Return Addresses: 
Computers switch context lots of times a second to allow them to deal with interrupts from a multitude of sources. When something interrupts them, such as a keyboard entry perhaps, the computer will execute the interrupt and then return to whatever task it was completing before. How it knows where to return in the code, is by adding the address of that particular point where it stopped - the return address - as well as the miscellaneous parameters that the code needed to execute, onto a LIFO structure known as the stack. These miscellaneous parameters, such as our array, are stored before the pointer and as such, by overflowing the array, we are able to overwrite whatever return address was in stored at the pointer(’s address) which paves the way for all sorts of shenanigans.
Most common of these shenanigans: - Actually writing code into an overflowed buffer and addressing the pointer to the location of this code - Getting a shell open 
Overflowing the array is most commonly done with a NOP Sled, which is simply consisted of a bunch of NOPs (no operation commands) that serve to pad the buffer up to the memory/stack address containing the return address and your payload which can be either a memory address pointing to your code or pointing to whatever would open up a shell.  This requires us to know the # of NOPs to place into our sled, which can be done in a variety of methods that the course doesn’t require us to know.
*will add more to this section as I read more on it* 
NIST and the History of Ciphers
Even after WWII, ciphers were not particularly powerful and for a while there was a ‘crypto black hole’ where no new cryptographic methods were being devised and nobody was aware of any principles one should follow. This changed with the advent of computers and eventually, groups concerned about security put out a standard known as NIST. Except noone knew what to put into the standard and so a competition was held which noone except IBM entered into and they won by default. And so IBM’s DES was adopted and had at the time, only 56 bits.  Then the NSA comes along, looks at DES, breaks it in two seconds using their differential cryptographic methods and says ‘yeah it’s okay keep using it XD’. 
Except everyone was like HANG ON, and eventually a successor AES was built. AES was predicated, much like DES, on performing many permutations, transposing and other obfuscating measures, which created an encryption method that was difficult to break feasibly, but had significantly more bits than AES.  XSS (Cross Site Scripting) or why Javascript is awful Cross Site Scripting 
Involved placing Javascript on a webpage, for example in a poorly secured forum, where you know unassuming people would visit. The Javascript will execute upon that page opening and whatever was in the JS will proceed to wreak havoc.  Common attacks include stealing your cookies to impersonate you.
SQL & Command Injections 
Webpages that require you to enter your username and password into fields will typically take the characters you entered as your username and password, stick them in an SQL query and execute said query to check your username and password against a preexisting username and password database. 
Instead of entering our usernames and passwords, we can enter actual SQL code which will actually execute, due to the nature of PHP converting your input into code. This wouldn’t work in any other language. For example:
Here’s an example query taken off https://www.acunetix.com/websitesecurity/sql-injection/
# Define POST variables uname = request.POST['username'] passwd = request.POST['password'] # SQL query vulnerable to SQLi sql = “SELECT id FROM users WHERE username=’” + uname + “’ AND password=’” + passwd + “’” # Execute the SQL statement database.execute(sql)
Now, we could easily input as the password:
password' OR 1=1
which would cause:
SELECT id FROM users WHERE username='username' AND password='password' OR 1=1'
SELECT id FROM users WHERE username=‘username’ AND password=‘password OR 1=1′
to execute, which would return the first ID of the first user in the database table due to that 1=1 is always true and the query is made complete by the ‘ appended to the word password. 
We could easily modify this query to print out the entire table if we wanted to write more code. 
Command injections rely on the same concept of writing code into input boxes, but instead we write shell code and grep our way to sensitive data. 
Cryptocurrency
Wasn’t really paying attention to this part, I’ll fill it in later
Block Modes 
How we combine individually ciphered blocks of a ciphertext, like we did in the Merkle-Damgard hash (recall that the input was split into blocks), to get a whole ciphertext:
- Can concatenate them like in WEP - Or more commonly, we can use CBC which is really convoluted: here’s some reading if you’re interested, but basically each unciphered block is XOR’d with the previous block. 
https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_(CBC)
Authentication - WIP 
How? What decisions?
Humans are bad at looking at      faces
No point in confidentiality, if there is no authentication
Defence in depth 
Something you know
Have: let's send someone an SMS when they type their PW WOW.
2FA worked well initially, however, SMS is easy to intercept.
Have single point of weakness, in your phone
Are:
Requires secrets to be     confidential, keyloggers, shoulder surfing etc.
NaĂŻve but easy to implement
1 note ¡ View note
codesolutionsstuff ¡ 3 years ago
Text
Most Important Array Methods in JavaScript
Tumblr media
Understand the Array in JS  Similar to arrays in other programming languages, the Array object permits the storage of a collection of various elements under a single variable name and provides members for carrying out standard array operations.
1. forEach
For each element in an array, the forEach() method performs the specified function once. For each entry in an array, in ascending index order, forEach() calls the callbackFn function supplied once. When an index property is uninitialized or deleted, it is not called. array.forEach(callback); const array1 = ; array1.forEach(element => console.log(element)); // expected output: "a" // expected output: "b" // expected output: "c"
2. map
Using a callback function, you can iterate through an array's elements using the Array.map() method. The items of the array will then each receive an execution of the callback function. array.map(callback); let arr = ; let modifiedArr = arr.map(function(element){ return element *3; }); console.log(modifiedArr); // The Array.map() method is frequently used to make modifications to the elements, whether you want to multiply by a certain amount, like in the code above, or do any other operations that your application might need.
3. concat
In JavaScript, concat() is a string method that is used to append one or more strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string. Concat() is a String method, and therefore must be called through a particular instance of the String class. array.concat(value1, value2, ..., valueN); const array1 = ; const array2 = ; const array3 = array1.concat(array2); console.log(array3); // expected output: Array
4. push
The array push() method in Javascript appends the specified element(s) to the end of the array and returns the length of the new array. Push is used to add an element to the end of an array (). array.push(element1, ..., elementN); const countries = ; countries.push("Kenya"); console.log(countries); //
5. pop
The pop() function returns the value of the last element removed from an array to the caller. When called on an empty array, pop() returns undefined. Array.prototype. The behavior of shift() is identical to that of pop(), but it is applied to the first element of an array. array.pop(); const plants = ; console.log(plants.pop()); // expected output: "tomato" console.log(plants); // expected output: Array
6. splice
The splice() function is a general-purpose technique that can be used to change the contents of an array by removing, replacing, or adding components in defined points. This section will explain how to apply this strategy to a specific area. array.splice(index, howMany, ); const fruits = ; fruits.splice(2, 0, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango
7. slice
The slice() method returns a shallow copy of a piece of an array into a new array object chosen from start to end (end not included), where start and end indicate the indexes of the array's members. The original array will remain unchanged. array.slice( begin ); const animals = ; console.log(animals.slice(2)); // expected output: Array console.log(animals.slice(2, 4)); // expected output: Array
8. shift
shift() is a JavaScript built-in function that removes the first element from an array. The shift() function affects the JavaScript array with which you are working directly. shift() returns the item from the array that you deleted. The shift() function deletes the item at index position 0 and reduces the values at subsequent index numbers by one. array.shift(); const array1 = ; const firstElement = array1.shift(); console.log(array1); // expected output: Array console.log(firstElement); // expected output: 1
9. unshift
The unshift() method puts the specified values at the start of an array-like object. Array.prototype.Push() behaves similarly to unshift(), but it is applied to the end of an array. array.unshift( element1, ..., elementN ); const array1 = ; console.log(array1.unshift(4, 5)); // expected output: 5 console.log(array1); // expected output: Array
10. join
JavaScript array join() is a built-in method that concatenates all of the array's components to construct and return a new string. The join() method merges the array's contents into a string and returns it. The array of elements will be separated by the separator given. A comma is the default separator (,). array.join(separator); const elements = ; console.log(elements.join()); // expected output: "Fire,Air,Water" console.log(elements.join('')); // expected output: "FireAirWater" console.log(elements.join('-')); // expected output: "Fire-Air-Water"
11. every
The every() method determines whether all array elements pass the test implemented by the provided function. It yields a Boolean value. array.every(callback); const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = ; console.log(array1.every(isBelowThreshold)); // expected output: true
12. filter
The filter() method returns a shallow duplicate of a piece of a given array that has been filtered down to only the elements of the given array that pass the test defined by the provided function. array.filter(callback); const words = ; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array 13. indexOf The indexOf() method returns the first index in the array at which a specified element can be found, or -1 if it does not exist. array.indexOf(searchElement); const beasts = ; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4 console.log(beasts.indexOf('giraffe')); // expected output: -1
14. reduce
The reduce() method calls a user-supplied "reducer" callback function on each element of the array in turn, sending in the result of the previous element's calculation. The outcome of running the reducer across all array elements is a single value. array.reduce(callback); const array1 = ; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (previousValue, currentValue) => previousValue + currentValue, initialValue ); console.log(sumWithInitial)
15. reverse
The reverse() method reverses an array in place and returns a reference to it, with the first array element becoming the last and the last array element becoming the first. In other words, the array's element order will be flipped in the opposite direction as previously mentioned. array.reverse(); const array1 = ; console.log('array1:', array1); // expected output: "array1:" Array const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array // Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // expected output: "array1:" Array 16. sort The sort() method sorts an array's items in situ and returns a reference to the sorted array. The ascending sort order is created by turning the elements into strings and then comparing their sequences of UTF-16 code unit values. array.sort( compareFunction ); const months = ; months.sort(); console.log(months); // expected output: Array const array1 = ; array1.sort(); console.log(array1); // expected output: Array 17. toString The function toString() { }() method returns a string containing the object's name. array.toString(); function Dog(name) { this.name = name; } const dog1 = new Dog('Gabby'); Dog.prototype.toString = function dogToString() { return `${this.name}`; }; console.log(dog1.toString()); // expected output: "Gabby"
18. at
The at() method accepts an integer value and returns the item at that index, which can be positive or negative. Negative integers count backwards from the array's last member. array.at(index) const array1 = ; let index = 2; console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`); // expected output: "Using an index of 2 the item returned is 8" index = -2; console.log(`Using an index of ${index} item returned is ${array1.at(index)}`); // expected output: "Using an index of -2 item returned is 130"
19. find
The find() method returns the first element in the specified array that meets the testing function. Undefined is returned if no values satisfy the testing function. array.find(function(currentValue, index, arr),thisValue) const array1 = ; const found = array1.find(element => element > 10); console.log(found); // expected output: 12
20. some
The some() method determines whether at least one array element passes the test implemented by the provided function. It returns true if it finds an element in the array for which the specified function returns true; otherwise, it returns false. It makes no changes to the array. array.some(callback); const array = ; // checks whether an element is even const even = (element) => element % 2 === 0; console.log(array.some(even)); // expected output: true Read the full article
0 notes
junctiongreys ¡ 3 years ago
Text
Npm minify
Tumblr media
NPM MINIFY HOW TO
NPM MINIFY INSTALL
NPM MINIFY CODE
Webpack 5.5.0 compiled successfully in 6388 ms If you build the project now ( npm run build), you should notice that CSS has become smaller as it's missing comments and has been concatenated: ⏥ webpack: Build FinishedĪsset vendor.js 126 KiB (name: vendor ) (id hint: commons ) 2 related assetsĪsset main.js 3.32 KiB (name: main ) 2 related assetsĪsset 34.js 247 bytes 2 related assetsĪsset main.css 730 bytes (name: main ). const TerserPlugin = require ( "terser-webpack-plugin" ) To attach it to the configuration, define a part for it first: To get started, include the plugin to the project: npm add terser-webpack-plugin -develop To tune the defaults, we'll attach terser-webpack-plugin to the project so that it's possible to adjust it. In webpack, minification process is controlled through two configuration fields: optimization.minimize flag to toggle it and optimization.minimizer array to configure the process. Modifying JavaScript minification process #
NPM MINIFY CODE
Rewriting the parameters breaks code unless you take precautions against it in this case. For example, Angular 1 expects specific function parameter naming when using modules. Unsafe transformations can break code as they can lose something implicit the underlying code relies upon. Good examples of this include renaming variables or even removing entire blocks of code based on the fact that they are unreachable ( if (false)). Safe transformations do this without losing any meaning by rewriting code. The point of minification is to convert the code into a smaller form.
NPM MINIFY HOW TO
Compared to UglifyJS, the earlier standard for many projects, it's a future-oriented option.ÄŞlthough webpack minifies the output by default, it's good to understand how to customize the behavior should you want to adjust it further or replace the minifier. Terser is an ES2015+ compatible JavaScript-minifier.
In package.Since webpack 4, the production output gets minified using terser by default.
NPM MINIFY INSTALL
It is possible to install two copies - global and local - like this: npm install uglify-js -global -save-dev The advantage of using -save-dev is that the dependency is listed in package.json so that when your code is placed on a different machine, running npm install installs all dependencies (except global ones). If you install globally with npm install -global uglifyjs, you don’t have to do this. node_modules/.bin/uglifyjs instead of just uglifyjs. node_modules/bin and if you want to run it directly from the command-line you need to write. Note: npm tools installed with -save-dev are located in.
Install in a terminal with npm install -save-dev uglify-js.
Major web browsers will run the minified code but show you the original code when you use their debugger).ÄŹonfusingly there are two packages, uglify-js and uglify-es. Uglify can also produce a source map to your original TypeScript or ES6 code (source maps allow you to debug the minified code as if it was the original. Uglify-js is 100 times larger than jsmin ( 1.5MB vs 15KB) but has many more features, is more popular, and is still small compared to WebPack or the TypeScript compiler. "build" : "tsc -declaration & npm run minify" ,
In package.json in the "scripts" section, add a minify script that uses jsmin (replace name with the name of your JavaScript file, not your TypeScript file multiple filenames are allowed):.
Install in a terminal with npm install -save-dev jsmin.
It just removes spaces it does not shorten variable names so it does not provide the smallest possible size. This is a tiny (15KB), simple and old minifier, appropriate for simple programs/modules. Parcel’s production mode, parcel build, also uses a minifier. If you’re using webpack to build your code, webpack -p reportedly minifies the application using “UglifyJSPlugin”. tsc -declaration & tsc -removeComments) 1. As of 2018 there is no compiler option to avoid this (at least you can remove comments with "removeComments":true, but if you are producing a d.ts file this will also remove comments from the d.ts file unless you perform a separate comment-removing build that does not produce a d.ts file, e.g. Even if your TypeScript code uses two spaces for indentation and has compact expressions like x+1, the TypeScript compiler produces output with four spaces and adds spaces between things like x + 1. Unfortunately, the TypeScript compiler not only cannot produce minified output, it proactively wastes space. Obfuscators are closely related - their goal is to make code harder to understand. For this reason, we have minifiers to remove spaces, remove newlines and shorten variable names to a single character. Since web apps are sent over the internet, it’s good to keep them small so that the app loads quickly. Leave a comment Four ways to minify your code
Tumblr media
0 notes
snarp ¡ 8 years ago
Text
Interesting Javascript Facts
* In Javascript, the addition operator is a lowercase letter 't' rather than the usual ‘+’.
* In Javascript, the equality operator is ‘+’.
* Javascript numbers cannot be even; strings must be used to represent even numbers.
* Javascript does not have arrays. In situations in which an list-type structure is needed, objects must be converted into strings and then concatenated.
* Javascript does not have data structures. It's on the floor.
* Javascript strings cannot be more than 69 characters long. That's the sex number.
* Javascript characters are two characters long.
* The main character of Javascript is Dracula. (Javascript is the only programming language to have a main character.)
* "Javascript" is commonly shortened to "JS," which stands for "Jerpin Sir."
* Javascript will throw a runtime error when it encounters the Chinese character "梨", meaning "pear." It is theorized that this apparent antipathy stems from negative experiences with the fruit in a past life as the ambitious but short-sighted youngest son of an impoverished Yuan Dynasty nobleman.
* Javascript was written by one person in less than two weeks.
* The “If” operator is spelled “Bif”.
1K notes ¡ View notes
obscurejavascript ¡ 7 years ago
Text
Deep Array Flattening in JavaScript
Firstly, deep flattening is available in many libraries libraries like lodash. But it is important to have a high level understanding og the building blocks like libraries that your application uses if you are doing anything complex. Firstly, here is the basic flatten:
function flatten(arr) { return [].concat(...arr); } const arr1 = [1,[2, [3, [4]]], 5]; console.info(flatten(arr1)); // [ 1, 2, [ 3, [ 4 ] ], 5 ]
It just takes an array then concatenates each item of the array resulting in an array with one less level. concat takes multiple arguments and the ... turns the array into a list of arguments to send into concat.
Flatten deep just takes that concept and applies across an array recursively:
function deepFlatten(arr) { const result = arr.map((element) => { if (element instanceof Array) { return deepFlatten(element); } return element; }); return flatten(result); } console.info(deepFlatten(arr1)); // [ 1, 2, 3, 4, 5 ]
In other words deep flattening will require looping through all array and sub array elements at least once. Note the above was written for readability, not performance. Libraries will probably do a lot of optimizations to make the above faster.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/deepFlatten.js
16 notes ¡ View notes
nerdsprite ¡ 3 years ago
Link
If you are JavaScript and then you have to work with JavaScript join() method more often. You may confused sometime how it actually works behind the scenes , what it will return for null or undefined value. Then this article is for you. Here we have explained Array.Join() Method in so deep that after going through this article you will be master of this method and can use more easily. So check this article  - JavaScript Join() 
https://nerdsprite.com/technology/javascript-join-array/
0 notes
codiens ¡ 4 years ago
Photo
Tumblr media
Best Javascript Training in Dehradun | Best JavaScript classes in Dehradun
Codiens institute offers real-time and place-focused Javascript training Dehradun. Our advanced Javascript course offers basic to advanced level training and is guaranteed to land you in good MNC companies all over the globe. Our Javascript trainers are Oracle sun Java certified professionals, with 10 years of experience working as professionals with multiple Javascript projects knowledge. To help students achieve their career goals, we have created our Javascript course content and syllabus.
Codiens is near Graphic Era Hill University and offers Javascript Training at multiple locations in Dehradun. Our advanced Javascript training centers have excellent infrastructure and lab facilities. Students in Dehradun also have access to advanced javascript certification courses. Our javascript training centers have more than 4000 students. The placement has been provided for 3567 of them. Javascript training in Dehradun is available on-site, online, or weekend classes.
Javascript Syllabus and Course Content in Dehradun
JavaScript Course Content
Overview of Java Script
Java Script: What's the Deal?
Comparing Products
JavaScript and JavaScript: A Comparison
The Java Script's Purpose
Prerequisites
Java Script Program Building
JavaScript in an HTML Doc
Java Script hiding from old Web Browsers
Review HTML
Layout and Text Formatting
Hypertext Links & Anchors
Tables
Forms
Frames
Java Script Commands Basic Syntax
Basic Commands
Variables
Overview of Variables
Assigning values to variables
Concatenating String Variables
Functions
Creating and calling function
Send Parameters To A Function
Parameters to be received out of a function
Variable scope & Lifetime
Events Call for Functions
Flow Control Structures
If Structure
If You Have Another Structure
For Loop
Loop
For/in Structure
Operators
Unary Operators
Numeric Operators
Logical Operators
String Processing
Length
Convert to all Lower or Upper Case
Index of
Last Index
Char at
Substr.
Objects
Standard Java Script functions
Making an object
Adding Functions To An Object
Multiple instances of an object type
History is an object
Accessing the History Object
Making Buttons
History. Go Method
Date
Create a Date Object
Only one string is needed to set the Date and Time
Separate Variables using Commas
Displaying the date and time
Time Zones
Extracting the Date
Extracting the Hrs
Date Setting Method
Set the Time
Non-Data Object Functionalities
Using objects such as Arrays
How to Create an Array
For Loop
Events
Time Status
Buttons
Location objects
Loading web pages from clients hard drives
Receive a Document from the Web Server
Hypertext and anchor links
Tracking the on-click Event
Form Objects
Button objects
Text Objects
Text Area Objects
Hidden Objects
Check Box Objects
Radio Button Objects
Selecting the right object
The Impact of Change
HTTP Cookies
The Cookie Property
Cookie Property
GetCookie()
SetCookie()
DeleteCookie()
Scope
Lifetime
Calendar Application
Static Calendar
Dynamic Calendar
Functions for updating the calendar
Assigning values for the dates of each month
Math Object
Constants
Circumference Calculator App
Functions
Frames
Referencing Objects In Other Frames
Event Calendar
Shopping Cart Application
Order Entry on the Internet
Looking at the Parent Object
An Array of Objects
Order Now
Place an Order
Validation of the Form
The Art of Trapping Empty Fields
Finding invalid values
Intercept the Submit Button
Java Applets
Java Applets Integrated with HTML
Regular Classes (morning, daytime, and evening)
Duration: 3 Weeks
Our Javascript Trainers
Javascript Technologies more than 10 years experience
A part of more than 10 Javascript projects in real-time
Dehradun MNC Company
4000+ students have been trained so far.
Solid Theoretical and Practical Knowledge
Javascript Certified Professionals
Dehradun Javascript (advanced javascript) Training
More than 4000+ students have been trained
3567 students placed
2000 Interviews Organization
If this blog is informative for you visit codiens website for more information .Read more
0 notes
anekobyte ¡ 3 years ago
Note
Sorry, life happened yesterday. You absolutely may!
I got this particular arcane snippet from GitHub user bluewings' Weird JavaScript generator. The general premise is as follows:
As demonstrated in the original post, for better or for worse, JavaScript is known for its aggressive use of implicit type conversion. Strings can be coerced into numbers...
Tumblr media
Numbers can be coerced into strings...
Tumblr media
And so on. The rules governing these conversions are well documented and explained at the resource linked above. Definitely give it a read if you develop with JavaScript!
Bearing this rich implicit coercion system in mind, how did we construct the string 'incredible' without typing even a single alphanumeric character or quotation mark? You may have guessed, from lookin', that Arrays are the key.
Arrays can be coerced into strings with + concatenation:
Tumblr media
And consequently can coerce other values into strings with + concatenation:
Tumblr media
And can be coerced into the values they can coerce into strings:
Tumblr media
And thus, by abusing square brackets and operations upon them, we can produce a rudimentary alphabet (with help from Objects):
Tumblr media
We could also get NaN and Infinity from coercing Objects, but these characters will do for now.
"But Aneko," I hear you say, "how do we get from that mess to words?" Well, dear reader, if you look closely at the original snippet you may notice a recurring pattern:
( <scary stuff> )[ <scary stuff> ] + ( <scary stuff> )[ <scary stuff> ] + ( <scary stuff> )[ <scary stuff> ] + …
The <scary stuff> in parentheses is some expression that yields a string, which we index using the <scary stuff> in square brackets. Wait, index? With integers? Yes! Arrays can be coerced into booleans and strings which can be coerced into numbers! Magical!
Tumblr media
(It's fine that the last one is a string because integer indices are actually strings on the backend anyways.)
This reply being long enough as it is, I won't include a breakdown of the entire snippet (you can get that from the generator linked above), but the first character is obtained like this:
(
![] // false
+ [] // coerces into "" via concatenation, making the whole expression result in a string
+ [][[]] // undefined
) // we now have "falseundefined", we want the "i" at index 10
[
+ // force number conversion
!![] // double-negated truthy object is true, converts to 1
+ // force string coercion with concatenation
[+[]] // coerces to [+""] coerces to [0] coerces to "0"
] // ["falseundefined"]["10"] yields "i"
Is it hard to program in Javascript? My teachers said it was hell
It's not hard it's just that javascript is a weird language to work with
Tumblr media
171 notes ¡ View notes
risebird ¡ 8 years ago
Text
Make music with JavaScript
Tumblr media
This summer, I was fortunate to see a presentation by Walmik, a sprint monkey at PayPal (@_walmik), which included an entire dimension of software engineering that I had not come across before: music. Turns out that Walmik created an npm-packaged JavaScript library called scribbletune, which makes it easy to create midi files with code. Yes, that’s right, with code, as in JavaScript. This open-source piece of software really just “uses noise that you already have, to make music”. It does this by allowing you to use scales, notes, and chords, in creating patterns represented by JavaScript arrays. So now you can use your lodash or underscore expertise to shape musical structures. That’s pretty cool.
You require sribbletune like any other node package, and essentially, start using this minimal API by invoking one of the following methods:
clip() - creates a measure of music, configured with many properties including ‘notes’ and ‘pattern’
scale() - creates a set of musical notes ordered by pitch
chord() - creates commonly used chords
midi() - generates a midi file
Using the above methods in combination, allows you to create a midi file that is shaped by your program. The file is driven by a midi pattern which you synthesize abstractly by manipulating JavaScript arrays. The pattern arrays basically consist of one character strings that represent whether to make a sound or not in that part of the pattern. You can use all of the same techniques that you normally use in JavaScript to manipulate these arrays, like map(), filter(), repeat(), or reduce(). The arrays can be concatenated and organized in complex code structures that allow you to “plug and play” musical patterns as you please, or rather, your code pleases.
The characters in the pattern arrays are usually either a ‘x’ (on), ’-‘ (off), or a ‘_’ (sustain). If you’ve ever created a pattern on a physical or virtual drum machine, then you can appreciate the (almost) boolean state each ‘bar’ can be in. When the “light is on”, the software will create a midi sound in its place (perhaps a kick drum?); and when the “light is off”, the sound is not made. The generated scale arrays can be morphed with array filtering, like when using the % (modulus) operator, and there’s even a property called ‘sizzle’ that gives your music a ‘human’ touch. You can use the ‘nodeLength’ property to shorten or lengthen your notes to really get the right sound pattern down.
Basically, you are just working with patterns. But to a programmer with some experience, this can be quite easy, and could even be faster than using actual industry software to create unique patterns for songs. You can manipulate these patterns in many different ways: slice them, dice them, glue them back together, maybe even throw them up into the air and see what falls into the basket? But seriously, it can be difficult to describe the kind of creativity that can be unleashed when you combine an industry trade with the dynamic art of creating music. This is where code turns into creativity through the medium of sound.
Once your scribbletune JavaScript is ready, you run it on your node server and it will generate a fully functional midi file. You can do everything you normally do with a midi file, including plugging it directly into music production software like Ableton. In fact, once it is loaded into such software, you can even change your code, rerun your script, and your pattern will be updated on the fly, since the file is usually read directly. In doing this, you can create a different midi pattern for each different instrument of an orchestra (or whatever is available to you in your music production software), and play them all together for the full effect.
Hope you will make some JavaScript music soon!
8 notes ¡ View notes
tak4hir0 ¡ 5 years ago
Link
Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority! JavaScript has primitives, objects and functions. All of them are values. All are treated as objects, even primitives. PrimitivesNumber, boolean, string, undefined and null are primitives. NumberThere is only one number type in JavaScript, the 64-bit binary floating point type. Decimal numbers’ arithmetic is inexact. As you may already know, 0.1 + 0.2 does not make 0.3 . But with integers, the arithmetic is exact, so 1+2 === 3 . Numbers inherit methods from the Number.prototype object. Methods can be called on numbers: (123).toString(); //"123" (1.23).toFixed(1); //"1.2"There are functions for converting strings to numbers : Number.parseInt(), Number.parseFloat() and Number(): Number.parseInt("1") //1 Number.parseInt("text") //NaN Number.parseFloat("1.234") //1.234 Number("1") //1 Number("1.234") //1.234Invalid arithmetic operations or invalid conversions will not throw an exception, but will result in the NaN “Not-a-Number” value. Number.isNaN() can detect NaN . The + operator can add or concatenate. 1 + 1 //2 "1" + "1" //"11" 1 + "1" //"11"StringA string stores a series of Unicode characters. The text can be inside double quotes "" or single quotes ''. Strings inherit methods from String.prototype. They have methods like : substring(), indexOf() and concat() . "text".substring(1,3) //"ex" "text".indexOf('x') //2 "text".concat(" end") //"text end"Strings, like all primitives, are immutable. For example concat() doesn’t modify the existing string but creates a new one. BooleanA boolean has two values : true and false . The language has truthy and falsy values. false, null, undefined, ''(empty string), 0 and NaN are falsy. All other values, including all objects, are truthy. The truthy value is evaluated to true when executed in a boolean context. Falsy value is evaluated to false. Take a look at the next example displaying the false branch. let text = ''; if(text) { console.log("This is true"); } else { console.log("This is false"); }The equality operator is ===. The not equal operator is !== . VariablesVariables can be defined using var, let and const. var declares and optionally initializes a variable. Variables declared with var have a function scope. They are treated as declared at the top of the function. This is called variable hoisting. The let declaration has a block scope. The value of a variable that is not initialize is undefined . A variable declared with const cannot be reassigned. Its value, however, can still be mutable. const freezes the variable, Object.freeze() freezes the object. The const declaration has a block scope. ObjectsAn object is a dynamic collection of properties. The property key is a unique string. When a non string is used as the property key, it will be converted to a string. The property value can be a primitive, object, or function. The simplest way to create an object is to use an object literal: let obj = { message : "A message", doSomething : function() {} }There are two ways to access properties: dot notation and bracket notation. We can read, add, edit and remove an object’s properties at any time. get: object.name, object[expression]set: object.name = value, object[expression] = valuedelete: delete object.name, delete object[expression]let obj = {}; //create empty object obj.message = "A message"; //add property obj.message = "A new message"; //edit property delete obj.message; //delete propertyObjects can be used as maps. A simple map can be created using Object.create(null) : let french = Object.create(null); french["yes"] = "oui"; french["no"] = "non"; french["yes"];//"oui"All object’s properties are public. Object.keys() can be used to iterate over all properties. function logProperty(name){ console.log(name); //property name console.log(obj[name]); //property value } Object.keys(obj).forEach(logProperty);Object.assign() copies all properties from one object to another. An object can be cloned by copying all its properties to an empty object: let book = { title: "The good parts" }; let clone = Object.assign({}, book);An immutable object is an object that once created cannot be changed. If you want to make the object immutable, use Object.freeze() . Primitives vs ObjectsPrimitives (except null and undefined) are treated like objects, in the sense that they have methods but they are not objects. Numbers, strings, and booleans have object equivalent wrappers. These are the Number, String, and Boolean functions. In order to allow access to properties on primitives, JavaScript creates an wrapper object and then destroys it. The process of creating and destroying wrapper objects is optimized by the JavaScript engine. Primitives are immutable, and objects are mutable. ArrayArrays are indexed collections of values. Each value is an element. Elements are ordered and accessed by their index number. JavaScript has array-like objects. Arrays are implemented using objects. Indexes are converted to strings and used as names for retrieving values. A simple array like let arr = ['A', 'B', 'C'] is emulated using an object like the one below: { '0': 'A', '1': 'B', '2': 'C' }Note that arr[1] gives the same value as arr['1'] : arr[1] === arr['1'] . Removing values from the array with delete will leave holes. splice() can be used to avoid the problem, but it can be slow. let arr = ['A', 'B', 'C']; delete arr[1]; console.log(arr); // ['A', empty, 'C'] console.log(arr.length); // 3JavaScript’s arrays don’t throw “index out of range” exceptions. If the index is not available, it will return undefined. Stack and queue can easily be implemented using the array methods: let stack = []; stack.push(1); // [1] stack.push(2); // [1, 2] let last = stack.pop(); // [1] console.log(last); // 2 let queue = []; queue.push(1); // [1] queue.push(2); // [1, 2] let first = queue.shift();//[2] console.log(first); // 1FunctionsFunctions are independent units of behavior. Functions are objects. Functions can be assigned to variables, stored in objects or arrays, passed as an argument to other functions, and returned from functions. There are three ways to define a function: Function Declaration (aka Function Statement)Function Expression (aka Function Literal)Arrow FunctionThe Function Declarationfunction is the first keyword on the lineit must have a nameit can be used before definition. Function declarations are moved, or “hoisted”, to the top of their scope.function doSomething(){}The Function Expression function is not the first keyword on the linethe name is optional. There can be an anonymous function expression or a named function expression.it needs to be defined, then it can executeit can auto-execute after definition (called “IIFE” Immediately Invoked Function Expression)let doSomething = function() {}Arrow FunctionThe arrow function is a sugar syntax for creating an anonymous functionexpression. {};Arrow functions don’t have their own this and arguments. Function invocationA function, defined with the function keyword, can be invoked in different ways: doSomething(arguments)theObject.doSomething(arguments) theObject["doSomething"](arguments)new Constructor(arguments) doSomething.apply(theObject, [arguments]) doSomething.call(theObject, arguments)Functions can be invoked with more or fewer arguments than declared in the definition. The extra arguments will be ignored, and the missing parameters will be set to undefined. Functions (except arrow functions) have two pseudo-parameters: this and arguments. thisMethods are functions that are stored in objects. Functions are independent. In order for a function to know on which object to work onthis is used. this represents the function’s context. There is no point to use this when a function is invoked with the function form: doSomething(). In this case this is undefined or is the window object, depending if the strict mode is enabled or not. When a function is invoked with the method form theObject.doSomething(),this represents the object. When a function is used as a constructor new Constructor(), thisrepresents the newly created object. The value of this can be set with apply() or call():doSomething.apply(theObject). In this case this is the object sent as the first parameter to the method. The value of this depends on how the function was invoked, not where the function was defined. This is of course a source of confusion. argumentsThe arguments pseudo-parameter gives all the arguments used at invocation. It’s an array-like object, but not an array. It lacks the array methods. function log(message){ console.log(message); } function logAll(){ let args = Array.prototype.slice.call(arguments); return args.forEach(log); } logAll("msg1", "msg2", "msg3");An alternative is the new rest parameters syntax. This time args is an array object. function logAll(...args){ return args.forEach(log); }returnA function with no return statement returns undefined. Pay attention to the automatic semi-colon insertion when using return. The following function will not return an empty object, but rather an undefined one. function getObject(){ return { } } getObject()To avoid the issue, use { on the same line as return : function getObject(){ return { } }Dynamic TypingJavaScript has dynamic typing. Values have types, variables do not. Types can change at run time. function log(value){ console.log(value); } log(1); log("text"); log({message : "text"});The typeof() operator can check the type of a variable. let n = 1; typeof(n); //number let s = "text"; typeof(s); //string let fn = function() {}; typeof(fn); //functionA Single ThreadThe main JavaScript runtime is single threaded. Two functions can’t run at the same time. The runtime contains an Event Queue which stores a list of messages to be processed. There are no race conditions, no deadlocks.However, the code in the Event Queue needs to run fast. Otherwise the browser will become unresponsive and will ask to kill the task. ExceptionsJavaScript has an exception handling mechanism. It works like you may expect, by wrapping the code using the try/catch statement. The statement has a single catch block that handles all exceptions. It’s good to know that JavaScript sometimes has a preference for silent errors. The next code will not throw an exception when I try to modify a frozen object: let obj = Object.freeze({}); obj.message = "text";Strict mode eliminates some JavaScript silent errors. "use strict"; enables strict mode. Prototype PatternsObject.create(), constructor function, and class build objects over the prototype system. Consider the next example: let servicePrototype = { doSomething : function() {} } let service = Object.create(servicePrototype); console.log(service.__proto__ === servicePrototype); //trueObject.create() builds a new object service which has theservicePrototype object as its prototype. This means that doSomething() is available on the service object. It also means that the __proto__ property of service points to the servicePrototype object. Let’s now build a similar object using class. class Service { doSomething(){} } let service = new Service(); console.log(service.__proto__ === Service.prototype);All methods defined in the Service class will be added to theService.prototype object. Instances of the Service class will have the same prototype (Service.prototype) object. All instances will delegate method calls to the Service.prototype object. Methods are defined once onService.prototype and then inherited by all instances. Prototype chainObjects inherit from other objects. Each object has a prototype and inherits their properties from it. The prototype is available through the “hidden” property __proto__ . When you request a property which the object does not contain, JavaScript will look down the prototype chain until it either finds the requested property, or until it reaches the end of the chain. Functional PatternsJavaScript has first class functions and closures. These are concepts that open the way for Functional Programming in JavaScript. As a result, higher order functions are possible. filter(), map(), reduce() are the basic toolbox for working with arrays in a function style. filter() selects values from a list based on a predicate function that decides what values should be kept. map() transforms a list of values to another list of values using a mapping function. let numbers = [1,2,3,4,5,6]; function isEven(number){ return number % 2 === 0; } function doubleNumber(x){ return x*2; } let evenNumbers = numbers.filter(isEven); //2 4 6 let doubleNumbers = numbers.map(doubleNumber); //2 4 6 8 10 12reduce() reduces a list of values to one value. function addNumber(total, value){ return total + value; } function sum(...args){ return args.reduce(addNumber, 0); } sum(1,2,3); //6Closure is an inner function that has access to the parent function’s variables, even after the parent function has executed. Look at the next example: function createCount(){ let state = 0; return function count(){ state += 1; return state; } } let count = createCount(); console.log(count()); //1 console.log(count()); //2count() is a nested function. count() accesses the variable state from its parent. It survives the invocation of the parent function createCount().count() is a closure. A higher order function is a function that takes another function as an input, returns a function, or does both. filter(), map(), reduce() are higher-order functions. A pure function is a function that returns a value based only of its input. Pure functions don’t use variables from the outer functions. Pure functions cause no mutations. In the previous examples isEven(), doubleNumber(), addNumber() and sum()are pure functions. ConclusionThe power of JavaScript lies in its simplicity. Knowing the JavaScript fundamentals makes us better at understanding and using the language. Read Functional Architecture with React and Redux and learn how to build apps in function style. Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority! For more on applying functional programming techniques in React take a look at Functional React. You can find me on Medium and Twitter.
0 notes
wonbindatascience ¡ 6 years ago
Text
Python Tutorial
Python Syntax compared to other programming languages
Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
Comments
Comments start with a #
Multi Line Comments: triple quotes("""abcd""")
Variables
Global Variables
Data types
Tumblr media
Casting
int(), float(), str()
Strings are Arrays
a = "Hello, World!" print(a[1])
Range of Indexes
print(thislist[2:5]) #the item in position 5 is NOT included
print(thislist[-4:-1]) #Negative indexing means starting from the end of the list. #-4 (included) to index -1 (excluded) #Remember that the last item has the index -1
Copy a List
list2 = list1.copy() (O) list2 = list1 (X) #You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
Tumblr media
Dictionary
Loop Through a Dictionary
#keys for x in thisdict:  print(x)
#values for x in thisdict:  print(thisdict[x])
#values for x in thisdict.values():  print(x)
#both keys and values for x, y in thisdict.items():  print(x, y)
Removing Items
thisdict = {  "brand": "Ford",  "model": "Mustang",  "year": 1964 } thisdict.pop("model") print(thisdict)
Copy a Dictionary
dict2 = dict1 (X) dict2 = dict1.copy() (O)
If ... Else
Loops
while
execute a set of statements as long as a condition is true.
for
range(2, 6) means values from 2 to 6 (but not including 6)
range(2, 30, 3) means incrementing the sequence with 3 (default is 1)
break
can stop the loop even if the while condition is true
continue
can stop the current iteration, and continue with the next loop iteration
pass vs continue
After executing pass, this further statement would be executed. After continue, it wouldn't.
E.g. >>> a = [0, 1, 2] >>> for element in a: ...     if not element: ...         pass ...     print element ... 0 1 2 >>> for element in a: ...     if not element: ...         continue ...     print element ... 1 2
else
can run a block of code once when the condition no longer is true
i = 1 while i < 6:   print(i)   i += 1 else:   print("i is no longer less than 6")
Functions
Passing Multiple Arguments to a Function
*args (arbitrary arguments)
It allows you to pass a varying number of positional arguments.
This way the function will receive a tuple of arguments.
# sum_integers_args.py def my_sum(*args):    result = 0    # Iterating over the Python args tuple    for x in args:        result += x    return result print(my_sum(1, 2, 3))
**kwargs
It allows you to pass a varying number of keyword arguments.
This way the function will receive a dictionary of arguments.
# concatenate.py def concatenate(**kwargs):    result = ""    # Iterating over the Python kwargs dictionary    for arg in kwargs.values():        result += arg    return result print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
Unpacking With the Asterisk Operators: * & **
E.g.)
Tumblr media Tumblr media Tumblr media Tumblr media
Ordering Arguments in a Function
1) Standard arguments 2) *args arguments 3) **kwargs arguments
E.g.
Tumblr media Tumblr media
Lambda
is a small anonymous function.
E.g.)
x = lambda a : a + 10 print(x(5))
Syntax
lambda arguments : expression
Why Use Lambda Functions
The power of lambda is better shown when you use them as an anonymous function inside another function.
E.g. #use the same function definition to make both functions, in the same program: def myfunc(n):  return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) print(mytripler(11)) >>22 >>33
Class
Python is an object oriented programming language. A Class is like an object constructor, or a "blueprint" for creating objects.
E.g.)
Create a Class
class MyClass:  x = 5
Create Object
p1 = MyClass() print(p1.x)
__init__()
All classes have a function called __init__(), which is always executed when the class is being initiated. __init__() is also called constructor used for instantiating an object.
E.g.)
class car():    def __init__(self, model, color):        self.model = model        self.color = color         def show(self):        print("Model is", self.model )        print("color is", self.color )  audi = car("audi a4", "blue") ferrari = car("ferrari 488", "green")  audi.show() ferrari.show()
self
“self” represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python.
Classes vs Instances
The class = the blue print.
An instance = a virtual copy
“A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.”
https://www.codecademy.com/forum_questions/558cd3fc76b8fe06280002ce
https://www.tutorialspoint.com/python/python_classes_objects.htm
The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self.
__repr__()
The Meaning of Underscores in Python
https://dbader.org/blog/meaning-of-underscores-in-python
Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from and child class is the class that inherits from another class
Create a Parent Class
class Person:  def __init__(self, fname, lname):    self.firstname = fname    self.lastname = lname  def printname(self):    print(self.firstname, self.lastname) x = Person("John", "Doe") x.printname()
Create a Child Class
class Student(Person):  pass x = Student("Mike", "Olsen") x.printname()
When you add the __init__() function into the Student class, the Student class will no longer inherit the parent's __init__() function. <=> The child's __init__() function overrides the inheritance of the parent's __init__() function.
super()
Python also has a super() function that will make the child class inherit all the methods and properties from its parent
E.g.)
class Student(Person):  def __init__(self, fname, lname, year):    super().__init__(fname, lname)    self.graduationyear = year x = Student("Mike", "Olsen", 2019)
Modules
Modules vs Packages vs Libraries in Python
Module
Simply put, a module in python is a .py file that defines one or more function/classes which you intend to reuse.
e.g.) import calendar print(calendar.TextCalendar(firstweekday=6).formatyear(2015))
‘calendar’ = module
‘TextCalendar’ = a class in the ‘calendar’ module
‘firstweekday=6′ = initiating(constructor)
‘formatyear’ = a method
Package
A Python package refers to a directory of Python module(s).
Library
Unlike C or C++, the term library does not have any specific contextual meaning in p\Python. When used in Python, a library is used loosely to describe a collection of the core modules.
Dates
datetime module
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
E.g.)
import datetime x = datetime.datetime.now() print(x) >>2019-12-17 20:42:59.640906
strftime() method
for formatting date objects into readable strings.
E.g.)
import datetime x = datetime.datetime(2018, 6, 1) print(x.strftime("%Y-%m-%d")) >>2018-06-01
Tumblr media
(https://www.w3schools.com/python/python_datetime.asp)
JSON
JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.
Python has a built-in package called json, which can be used to work with JSON data.
import json
Parse JSON - Convert from JSON to Python
# some JSON: x =  '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"])
Convert from Python to JSON
# a Python object (dict): x = {  "name": "John",  "age": 30,  "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y)
RegEx
https://www.w3schools.com/python/python_regex.asp
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.
Python has a built-in package called ‘re’, which can be used to work with Regular Expressions.
import re
Functions
findall()
Returns a list containing all matches
If no matches are found, an empty list is returned
e.g.)
import re txt = "1The 2 rain 3in Spain45" x = re.findall("\d+", txt) print(x) >>> ['1', '2', '3', '45']
search()
Returns a Match object if there is a match anywhere in the string
If there is more than one match, only the first occurrence of the match will be returned
If no matches are found, the value None is returned:
split()
Returns a list where the string has been split at each match
sub()
Replaces one or many matches with a string
e.g.)
import re txt = "The rain in Spain" x = re.sub("\s", "9", txt) print(x) # Replace every white-space character with the number 9 >>> The9rain9in9Spain
Metacharacters
Metacharacters are characters with a special meaning:
Tumblr media
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Tumblr media
Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:
Tumblr media
Match Object
A Match Object is an object containing information about the search and the result.
If there is no match, the value None will be returned, instead of the Match Object.
The Match object has properties and methods used to retrieve information about the search, and the result:
.span() 
returns a tuple containing the start-, and end positions of the match.
.string
returns the string passed into the function
.group()
returns the part of the string where there was a match
Try Except
https://www.w3schools.com/python/python_try_except.asp
code
try
The try block lets you test a block of code for errors.
except
The except block lets you handle the error.
finally
The finally block lets you execute code, regardless of the result of the try- and except blocks.
e.g.
try:    print(1/0) except ZeroDivisionError as e:    print("Error Code:", e) except ValueError as e:    print('Error Code:', e) >> Error Code: division by zero
Raise
is used to raise an exception.You can define what kind of error to raise, and the text to print to the user.
code
x = -1 if x < 0:  raise Exception("Sorry, no numbers below zero")
User Input
String Formatting
if __name__ == __main__
https://stackoverflow.com/questions/419163/what-does-if-name-main-do
https://dojang.io/mod/page/view.php?id=2448
When the Python interpreter reads a source file, it first defines a few special variables. like ‘__name__’
When Your Module Is the Main Program
the interpreter will assign the hard-coded string "__main__" to the __name__ variable
When Your Module Is Imported By Another
the interpreter will assign the file name of your module to the __name__ variable
https://www.w3schools.com/python/python_intro.asp https://stackoverflow.com/questions/9483979/is-there-a-difference-between-continue-and-pass-in-a-for-loop-in-python/36952166 https://www.geeksforgeeks.org/self-in-python-class/ https://www.geeksforgeeks.org/constructors-in-python/ https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ https://knowpapa.com/modpaclib-py/ https://realpython.com/python-kwargs-and-args/
0 notes
charlotte-codes ¡ 6 years ago
Text
console.log(“Eek! It’s Javascript week!”);
Tumblr media
We’ve just finished two solid weeks of JavaScript and I’m trying to think how I can fit it all into one post. The answer is ... I can’t.
So instead I’m going to deliver it in manageable, bitesize chunks over the next few weeks. It’ll help me revise and keep everything fresh in my head. 
We’ve learnt A LOT thanks to our fantastic tutor, Mark.
Contrary to the image above, I think I do know what I’m doing, but I also think my brain might be melting. Again. 
Although we haven’t quite become one entity yet, if I were my MacBook, my cooling fan would be working overtime right now.
I’ve been dreaming about code the last few nights - it’s gradually permeating my subconscious, which is good (maybe). The other day I asked Pete what he wanted for dinner using an else if structure (‘if you want pasta then you’ll need to buy garlic bread, else if you want the rest of the curry I need you to get some naans on the way home, else we can just have it without’).
I’ve just finished a post about using JavaScript in the browser, which is coming out Tuesday. In the meantime, I thought I’d better just do a brief intro to JavaScript 101.
Let’s start by talking about types.
There are only a few basic types in JavaScript (we’ll get to functions, arrays and objects and so on in later posts). 
1) Strings 
Strings are a sequence of characters, e.g. text, numbers, emojis... 
They are wrapped in “double quotes” (or single quotes if you want to be a maverick). 
Tumblr media
The most fun things about strings is learning the words ‘concatenation’ and ‘interpolation’ so that you can impress your friends with your huge lexicon. Who needs a BMW?
Concatenation is how you add strings together and link strings to other types, like variables. You do this with a + operator and it’s pretty straightforward.
Tumblr media
I might as well talk briefly about variables here too.
You can see above that I’ve declared a variable called name using the word let (you can also use const if you won’t be redeclaring it later, or you might also see var being used instead of let). I like let because I’ve used it before in maths in a similar way. In fact, variables should be very familiar to anyone who remembers the fundamentals of GCSE algebra. 
A variable works kind of like a box that you store something in for later. It’s a bit like when you move house and you empty out various kitchen cupboards into a box that you write kitchen on so that you know where to find it again. In this instance, I’ve put a string into the box with the value Charlotte, then written the word name on the box. I can use it over and over again by calling on the variable, just as you can see in my string concatenation. The result logged to the console would be “Hello my name is Charlotte”. Notice also that I’ve left a space at the end of the first string. If I didn’t do that, it would look like crap (”Hello my name isCharlotte”).
Interpolation is similar but, in my opinion, looks cooler (I’ve never had cause to use backticks until now):
Tumblr media
There are various differences between concatenation and interpolation that I cannot be bothered to list in this post (which was meant to be brief). I’ll come back to it later. 
2) Numbers 
I mean, do you need me to tell you what numbers are? 
You can actually do fun mathsy stuff with these in JavaScript eg. (15 % 7). 
Tumblr media Tumblr media
Yum. 
% means modulus. It divides the two numbers and gives back the remainder. 
This was a new one for me. In A Level maths, modulus means an absolute value - the positive value of any number. The JavaScript operator uses the percentage sign, which is also mildly confusing to begin with if you are used to teaching maths. 
But we like numbers so we’ll roll with it. 
3) Booleans 
Booleans. Another nice word to bring out at parties. 
Named after the nineteenth-century mathematician, George Boole, Boolean logic is fun to say and fun to use. It’s fairly simple to understand too - relying purely on the values true and false. 
This is most useful when making comparisons, so there are many comparison operators that we can use that will give us Boolean values. Which one of these do you think would return ‘false’?
Tumblr media
It gets a little bit more complicated when we get to using and ( && ), or ( || ) and not ( ! ) or adding different types into our comparisons (”12″ does not equal 12 because one is a string and one is a number) ... 
Tumblr media
It’s starting to look serious now, so I’ll stop there for tonight. It’s midnight on a Saturday and I’m in bed revising basic JavaScript AND I COULDN’T BE HAPPIER. 
You can keep your all-night raves, I’m off to see if I can get anywhere with CodeWars.
0 notes
t-baba ¡ 6 years ago
Photo
Tumblr media
An Introduction to Gulp.js
Developers spend precious little time coding. Even if we ignore irritating meetings, much of the job involves basic tasks which can sap your working day:
generating HTML from templates and content files
compressing new and modified images
compiling Sass to CSS code
removing console and debugger statements from scripts
transpiling ES6 to cross-browser–compatible ES5 code
code linting and validation
concatenating and minifying CSS and JavaScript files
deploying files to development, staging and production servers.
Tasks must be repeated every time you make a change. You may start with good intentions, but the most infallible developer will forget to compress an image or two. Over time, pre-production tasks become increasingly arduous and time-consuming; you'll dread the inevitable content and template changes. It's mind-numbing, repetitive work. Wouldn’t it be better to spend your time on more profitable jobs?
If so, you need a task runner or build process.
That Sounds Scarily Complicated!
Creating a build process will take time. It's more complex than performing each task manually, but over the long term, you’ll save hours of effort, reduce human error and save your sanity. Adopt a pragmatic approach:
Automate the most frustrating tasks first.
Try not to over-complicate your build process. An hour or two is more than enough for the initial setup.
Choose task runner software and stick with it for a while. Don't switch to another option on a whim.
Some of the tools and concepts may be new to you, but take a deep breath and concentrate on one thing at a time.
Task Runners: the Options
Build tools such as GNU Make have been available for decades, but web-specific task runners are a relatively new phenomenon. The first to achieve critical mass was Grunt — a Node.js task runner which used plugins controlled (originally) by a JSON configuration file. Grunt was hugely successful, but there were a number of issues:
Grunt required plugins for basic functionality such as file watching.
Grunt plugins often performed multiple tasks, which made customisation more awkward.
JSON configuration could become unwieldy for all but the most basic tasks.
Tasks could run slowly because Grunt saved files between every processing step.
Many issues were addressed in later editions, but Gulp had already arrived and offered a number of improvements:
Features such as file watching were built in.
Gulp plugins were (mostly) designed to do a single job.
Gulp used JavaScript configuration code that was less verbose, easier to read, simpler to modify, and provided better flexibility.
Gulp was faster because it uses Node.js streams to pass data through a series of piped plugins. Files were only written at the end of the task.
Of course, Gulp itself isn't perfect, and new task runners such as Broccoli.js, Brunch and webpack have also been competing for developer attention. More recently, npm itself has been touted as a simpler option. All have their pros and cons, but Gulp remains the favorite and is currently used by more than 40% of web developers.
Gulp requires Node.js, but while some JavaScript knowledge is beneficial, developers from all web programming faiths will find it useful.
What About Gulp 4?
This tutorial describes how to use Gulp 3 — the most recent release version at the time of writing. Gulp 4 has been in development for some time but remains a beta product. It's possible to use or switch to Gulp 4, but I recommend sticking with version 3 until the final release.
Step 1: Install Node.js
Node.js can be downloaded for Windows, macOS and Linux from nodejs.org/download/. There are various options for installing from binaries, package managers and docker images, and full instructions are available.
Note for Windows users: Node.js and Gulp run on Windows, but some plugins may not install or run if they depend on native Linux binaries such as image compression libraries. One option for Windows 10 users is the new bash command-line, which solves many issues.
Once installed, open a command prompt and enter:
node -v
This reveals the version number. You're about to make heavy use of npm — the Node.js package manager which is used to install modules. Examine its version number:
npm -v
Note for Linux users: Node.js modules can be installed globally so they’re available throughout your system. However, most users will not have permission to write to the global directories unless npm commands are prefixed with sudo. There are a number of options to fix npm permissions and tools such as nvm can help, but I often change the default directory. For example, on Ubuntu/Debian-based platforms:
cd ~ mkdir .node_modules_global npm config set prefix=$HOME/.node_modules_global npm install npm -g
Then add the following line to the end of ~/.bashrc:
export PATH="$HOME/.node_modules_global/bin:$PATH"
Finally, update with this:
source ~/.bashrc
Step 2: Install Gulp Globally
Install Gulp command-line interface globally so the gulp command can be run from any project folder:
npm install gulp-cli -g
Verify Gulp has installed with this:
gulp -v
Step 3: Configure Your Project
Note for Node.js projects: you can skip this step if you already have a package.json configuration file.
Presume you have a new or pre-existing project in the folder project1. Navigate to this folder and initialize it with npm:
cd project1 npm init
You’ll be asked a series of questions. Enter a value or hit Return to accept defaults. A package.json file will be created on completion which stores your npm configuration settings.
Note for Git users: Node.js installs modules to a node_modules folder. You should add this to your .gitignore file to ensure they’re not committed to your repository. When deploying the project to another PC, you can run npm install to restore them.
For the remainder of this article, we'll presume your project folder contains the following sub-folders:
src folder: preprocessed source files
This contains further sub-folders:
html - HTML source files and templates
images — the original uncompressed images
js — multiple preprocessed script files
scss — multiple preprocessed Sass .scss files
build folder: compiled/processed files
Gulp will create files and create sub-folders as necessary:
html — compiled static HTML files
images — compressed images
js — a single concatenated and minified JavaScript file
css — a single compiled and minified CSS file
Your project will almost certainly be different but this structure is used for the examples below.
Tip: If you're on a Unix-based system and you just want to follow along with the tutorial, you can recreate the folder structure with the following command:
mkdir -p src/{html,images,js,scss} build/{html,images,js,css}
Step 4: Install Gulp Locally
You can now install Gulp in your project folder using the command:
npm install gulp --save-dev
This installs Gulp as a development dependency and the "devDependencies" section of package.json is updated accordingly. We’ll presume Gulp and all plugins are development dependencies for the remainder of this tutorial.
Alternative Deployment Options
Development dependencies are not installed when the NODE_ENV environment variable is set to production on your operating system. You would normally do this on your live server with the Mac/Linux command:
export NODE_ENV=production
Or on Windows:
set NODE_ENV=production
This tutorial presumes your assets will be compiled to the build folder and committed to your Git repository or uploaded directly to the server. However, it may be preferable to build assets on the live server if you want to change the way they are created. For example, HTML, CSS and JavaScript files are minified on production but not development environments. In that case, use the --save option for Gulp and all plugins, i.e.
npm install gulp --save
This sets Gulp as an application dependency in the "dependencies" section of package.json. It will be installed when you enter npm install and can be run wherever the project is deployed. You can remove the build folder from your repository since the files can be created on any platform when required.
Step 4: Create a Gulp Configuration File
Create a new gulpfile.js configuration file in the root of your project folder. Add some basic code to get started:
// Gulp.js configuration var // modules gulp = require('gulp'), // development mode? devBuild = (process.env.NODE_ENV !== 'production'), // folders folder = { src: 'src/', build: 'build/' } ;
This references the Gulp module, sets a devBuild variable to true when running in development (or non-production mode) and defines the source and build folder locations.
ES6 note: ES5-compatible JavaScript code is provided in this tutorial. This will work for all versions of Gulp and Node.js with or without the --harmony flag. Most ES6 features are supported in Node 6 and above so feel free to use arrow functions, let, const, etc. if you're using a recent version.
gulpfile.js won't do anything yet because you need to …
Step 5: Create Gulp Tasks
On its own, Gulp does nothing. You must:
install Gulp plugins, and
write tasks which utilize those plugins to do something useful.
It's possible to write your own plugins but, since almost 3,000 are available, it's unlikely you'll ever need to. You can search using Gulp's own directory at gulpjs.com/plugins/, on npmjs.com, or search "gulp something" to harness the mighty power of Google.
Gulp provides three primary task methods:
gulp.task — defines a new task with a name, optional array of dependencies and a function.
gulp.src — sets the folder where source files are located.
gulp.dest — sets the destination folder where build files will be placed.
Any number of plugin calls are set with pipe between the .src and .dest.
The post An Introduction to Gulp.js appeared first on SitePoint.
by Craig Buckler via SitePoint http://bit.ly/2PBh4vG
0 notes